import axios from 'axios';

// 1.创建axios实例
const service = axios.create({
  baseURL: 'http://127.0.0.1:3000',
  timeout: 5000,
});

// 2.请求拦截器
service.interceptors.request.use(
  (config) => {
    // 判断本地有没有token，有则在请求头加上authorization
    const token = sessionStorage.getItem('token') || "";
    // console.log(token,'token')
    if (token) {
      config.headers = {
        ...config.headers,
        authorization: `Bearer ${token}`,
      }
    }
    // console.log(config, '请求拦截');
    return config;
  },
  (error) => Promise.reject(error)
);

// 3.响应拦截器
service.interceptors.response.use(
  (response) => {
    // console.log(response,'响应拦截1');
    // 判断响应码是否正常
    if (response.data.code !== 200) {
      return null;
    }
    // 判断是否有authorization属性
    if (response.headers.authorization) {
      // 存储在本地 (Bearer token)
      const token = response.headers.authorization.split(' ')[1];
      sessionStorage.token = token;
    }
    // console.log(response,'response');
    // 修改了headers为header
    // console.log(response.headers,'headers')
    // console.log(response,'响应拦截2');
    return response.data.data;
  },
  (error) => {
    // console.log(error,'拦截错误输出')
    Promise.reject(error)
  }
);

// 4.默认导出实例
export default service;